<?php

class ApiController extends ResfulController
{
	public function actionIndex()
	{
		$this->render('index');
	}
    /**
     * @return array action filters
     */
    public function filters()
    {
    	return array();
    }
    
    // Actions
    public function actionList()
    {
    	// Get the respective model instance
        // $this->_checkAuth();
        $start = $_GET['start'];
        $limit = $_GET['limit'];
        $sort = $_GET['sort'];
        $dir = $_GET['dir'];
        $filters = isset($_REQUEST['filter']) ? $_REQUEST['filter'] : null;
         // print_r($filters);
        $where = ' 0 = 0 ';
        $qs = '';
        if (is_array($filters)) {
            $encoded = false;
        } else {
            $encoded = true;
            $filters = json_decode($filters);
        }
        // print_r($filters);
        if (is_array($filters)) {
            for ($i=0;$i<count($filters);$i++){
                $filter = $filters[$i];
                // assign filter data (location depends if encoded or not)
                if ($encoded) {
                    $field = $filter->property;
                    $value = $filter->value;
                    $compare = isset($filter->comparison) ? $filter->comparison : null;
                    $filterType = isset($filter->type)? $filter->type : '';
                } else {
                    $field = $filter['property'];
                    $value = $filter['data']['value'];
                    $compare = isset($filter['data']['comparison']) ? $filter['data']['comparison'] : null;
                    $filterType = isset($filter['data']['type'])? $filter['data']['type'] : '';
                }
                switch($filterType){
                    case 'string' : $qs .= " AND ".$field." LIKE '%".$value."%'"; Break;
                    case '' : $qs .= " AND ".$field." LIKE '%".$value."%'"; Break;
                    case 'list' :
                        if (strstr($value,',')){
                            $fi = explode(',',$value);
                            for ($q=0;$q<count($fi);$q++){
                                $fi[$q] = "'".$fi[$q]."'";
                            }
                            $value = implode(',',$fi);
                            $qs .= " AND ".$field." IN (".$value.")";
                        }else{
                            $qs .= " AND ".$field." = '".$value."'";
                        }
                    Break;
                    case 'boolean' : $qs .= " AND ".$field." = ".($value); Break;
                    case 'numeric' :
                        switch ($compare) {
                            case 'eq' : $qs .= " AND ".$field." = ".$value; Break;
                            case 'lt' : $qs .= " AND ".$field." < ".$value; Break;
                            case 'gt' : $qs .= " AND ".$field." > ".$value; Break;
                            case 'khac' : $qs .= " AND ".$field." != ".$value; Break;
                        }
                    Break;
                    case 'date' :
                        switch ($compare) {
                            case 'eq' : $qs .= " AND DATE_FORMAT(".$field.",'%Y-%m-%d') = '".date('Y-m-d',strtotime($value))."'"; Break;
                            case 'lt' : $qs .= " AND ".$field." < '".date('Y-m-d',strtotime($value))."'"; Break;
                            case 'gt' : $qs .= " AND ".$field." > '".date('Y-m-d',strtotime($value))."'"; Break;
                        }
                    Break;
                }
            }
            $where .= $qs;
            // print_r($where);
        }

        $Criteria = new CDbCriteria();
    	switch($_GET['model'])
    	{
    		case 'orders':
              $Criteria->limit = $limit;
              $Criteria->offset = $start;
              $Criteria->order = $sort.' '.$dir;
              $Criteria->condition = $where; 
    		  $models = Orders::model()->findAll($Criteria);

              if (is_array($filters)) {
                $total = count($models);
              }else
                $total = count(Orders::model()->findAll());
              
    		  break;
            case 'orderdetails':
                $Criteria->limit = $limit;
                $Criteria->offset = $start;
                $Criteria->order = $sort.' '.$dir;
                $Criteria->condition = $where; 
                $models = Orderdetails::model()->findAll($Criteria);

                if (is_array($filters)) {
                    $total = count($models);
                  }else
                    $total = count(Orders::model()->findAll());
                break;
            case 'products':
                $Criteria->limit = $limit;
                $Criteria->offset = $start;
                $Criteria->order = $sort.' '.$dir;
                $Criteria->condition = $where; 
                $models = Products::model()->findAll($Criteria);

                if (is_array($filters)) {
                    $total = count($models);
                  }else
                    $total = count(Orders::model()->findAll());
                break;
            case 'status_order':
                $models = StatusOrder::model()->findAll();
                $total = count($models);
                break;
            case 'banks':
                $Criteria->limit = $limit;
                $Criteria->offset = $start;
                $Criteria->order = $sort.' '.$dir;
                $Criteria->condition = $where; 
                $models = BankAccount::model()->findAll($Criteria);
                $total = count($models);
                break;
            case 'accounts':
                $Criteria->limit = $limit;
                $Criteria->offset = $start;
                $Criteria->order = $sort.' '.$dir;
                $Criteria->condition = $where; 
                $models = Account::model()->findAll($Criteria);
                if (is_array($filters)) {
                    $total = count($models);
                  }else
                    $total = count(Account::model()->findAll());
                break;
    		default:
            // Model not implemented error
    		$this->_sendResponse(501, sprintf(
    			'Error: Mode <b>list</b> is not implemented for model <b>%s</b>',
    			$_GET['model']) );
    		Yii::app()->end();
    	}
    // Did we get some results?
    	if(empty($models)) {
            // No
    		// $this->_sendResponse(200, 
    		// 	sprintf('No items where found for model <b>%s</b>', $_GET['model']) );
            $rowModels['lists'] = '';
            // Send the response
            $this->_sendResponse(200, CJSON::encode($rowModels));

    	} else {
            // Prepare response
    		$rows = array();

    		foreach($models as $key=>$model){
    			$rows[$key] = $model->attributes;
                if($_GET['model']==='orders'){
                    $tinh = $model->tinh;
                    $acc = $model->account;
                    $tenkh = $acc->fullname;
                    $tinh_name = $tinh->tinh_name;
              
                    $rows[$key]['tinh_thanh'] = $tinh_name;
                    $rows[$key]['ten_khach_hang'] = $tenkh;
                }else if($_GET['model'] === 'orderdetails'){
                    $product = $model->product;
                    $cate = $product->cate;

                    $product_name = $product->product_name;
                    $product_price = $product->price;
                    $cate_name = $cate->cate_name;

                    $rows[$key]['product_name'] = $product_name;
                    $rows[$key]['product_cate'] = $cate_name;
                    $rows[$key]['price'] = $product_price;
                }
            }
            $rowModels['lists'] = $rows;
            $rowModels['totalCount'] = $total;
            // Send the response
    		$this->_sendResponse(200, CJSON::encode($rowModels));
    	}
    }
    
    public function actionView()
    {
         $this->_checkAuth();
        // Check if id was submitted via GET
        if(!isset($_GET['id']))
            $this->_sendResponse(500, 'Error: Parameter <b>id</b> is missing' );

        switch($_GET['model'])
        {
            // Find respective model    
            case 'orders' : 
                $model = Orders::model()->findByPk($_GET['id']);
                break;
            case 'orderDetail': // {{{ 
                $model = Orderdetails::model()->findByPk($_GET['id']);
                break; // }}} 
            default: // {{{ 
                $this->_sendResponse(501, sprintf('Mode <b>view</b> is not implemented for model <b>%s</b>',$_GET['model']) );
                exit; // }}} 
        }
        if(is_null($model)) {
            $this->_sendResponse(404, 'No Item found with id '.$_GET['id']);
        } else {
            $this->_sendResponse(200, $this->_getObjectEncoded($_GET['model'], $model->attributes));
        }
    }
    public function actionCreate()
    {
        $this->_checkAuth();

        switch($_GET['model'])
        {
            // Get an instance of the respective model
            case 'orders': // {{{ 
                $model = new Orders;                    
                break; // }}} 
            case 'orderdetails': // {{{ 
                $model = new Orderdetails;
                break;     
            case 'accounts': // {{{ 
                $model = new Account;                    
                break; // }}} 
            default: // {{{ 
                $this->_sendResponse(501, sprintf('Mode <b>create</b> is not implemented for model <b>%s</b>',$_GET['model']) );
                exit; // }}} 
        }
        $form_data = json_decode(file_get_contents('php://input'));
        // print_r($form_data);
        // Try to assign POST values to attributes
        foreach($form_data as $var=>$value) {
            // Does the model have this attribute?
            // print_r($var);
            if($_GET['model'] === 'orders'){
                if( ($var !== 'tinh_thanh') && ($var !== 'ten_khach_hang') ){
                    if($model->hasAttribute($var)) {
                        $model->$var = $value;
                    } else {
                        // No, raise an error
                        $this->_sendResponse(500, sprintf('Parameter <b>%s</b> is not allowed for model <b>%s</b>', $var, $_GET['model']) );
                    }
                }
            }else if($_GET['model'] === 'orderdetails'){
                if( ($var !== 'product_name') && ($var !== 'product_cate') && ($var !== 'price') ){
                    if($model->hasAttribute($var)) {
                        $model->$var = $value;
                    } else {
                        // No, raise an error
                        $this->_sendResponse(500, sprintf('Parameter <b>%s</b> is not allowed for model <b>%s</b>', $var, $_GET['model']) );
                    }
                }
            }else{
                if($model->hasAttribute($var)) {
                    $model->$var = $value;
                } else {
                    // No, raise an error
                    $this->_sendResponse(500, sprintf('Parameter <b>%s</b> is not allowed for model <b>%s</b>', $var, $_GET['model']) );
                }
            }

        }
        // Try to save the model
        if($model->save()) {
            // Saving was OK
            // $this->_sendResponse(200, $this->_getObjectEncoded($_GET['model'], $model->attributes) );
            echo json_encode(array("success" => true,'id'=>$model->id));
        } else {
            // Errors occurred
            $msg = "<h1>Error</h1>";
            $msg .= sprintf("Couldn't create model <b>%s</b>", $_GET['model']);
            $msg .= "<ul>";
            foreach($model->errors as $attribute=>$attr_errors) {
                $msg .= "<li>Attribute: $attribute</li>";
                $msg .= "<ul>";
                foreach($attr_errors as $attr_error) {
                    $msg .= "<li>$attr_error</li>";
                }        
                $msg .= "</ul>";
            }
            $msg .= "</ul>";
            $this->_sendResponse(500, $msg );
        }
    }
    public function actionUpdate()
    {
        $this->_checkAuth();

        // Get PUT parameters
        $form_data = json_decode(file_get_contents('php://input'));

        switch($_GET['model'])
        {
            // Find respective model
            case 'orders': // {{{ 
                $model = Orders::model()->findByPk($_GET['id']);                    
                break; // }}} 
            case 'accounts': // {{{ 
                $model = Account::model()->findByPk($_GET['id']);                    
                break; // }}} 
            default: // {{{ 
                $this->_sendResponse(501, sprintf('Error: Mode <b>update</b> is not implemented for model <b>%s</b>',$_GET['model']) );
                exit; // }}} 
        }
        if(is_null($model))
            $this->_sendResponse(400, sprintf("Error: Didn't find any model <b>%s</b> with ID <b>%s</b>.",$_GET['model'], $_GET['id']) );
        
        // Try to assign PUT parameters to attributes
        foreach($form_data as $var=>$value) {
            // Does model have this attribute?
           if($_GET['model'] === 'orders'){
                if( ($var !== 'tinh_thanh') && ($var !== 'ten_khach_hang') ){
                    if($model->hasAttribute($var)) {
                        $model->$var = $value;
                    }
                }
            }else if($_GET['model'] === 'orderdetails'){
                if( ($var !== 'product_name') && ($var !== 'product_cate') && ($var !== 'price') ){
                    if($model->hasAttribute($var)) {
                        $model->$var = $value;
                    }
                }
            }else{
                if($model->hasAttribute($var)) {
                    $model->$var = $value;
                } else {
                    // No, raise an error
                    $this->_sendResponse(500, sprintf('Parameter <b>%s</b> is not allowed for model <b>%s</b>', $var, $_GET['model']) );
                }
            }
        }
        // Try to save the model
        // print_r($model->note);
        if($model->save()) {
            //$this->_sendResponse(200, sprintf('The model <b>%s</b> with id <b>%s</b> has been updated.', $_GET['model'], $_GET['id']) );
            echo json_encode(array("success" => true,'id'=>$model->id));
        } else {
            $msg = "<h1>Error</h1>";
            $msg .= sprintf("Couldn't update model <b>%s</b>", $_GET['model']);
            $msg .= "<ul>";
            foreach($model->errors as $attribute=>$attr_errors) {
                $msg .= "<li>Attribute: $attribute</li>";
                $msg .= "<ul>";
                foreach($attr_errors as $attr_error) {
                    $msg .= "<li>$attr_error</li>";
                }        
                $msg .= "</ul>";
            }
            $msg .= "</ul>";
            $this->_sendResponse(500, $msg );
        }
    }
    public function actionDelete()
    {
    }
   

}